import {
    defineStore,
    createPinia
} from 'pinia';
import {getUserInfo, setUserInfo, getToken, setToken, getLoginStatus} from '@/utils/utils'
import {getUserInfo as getUserInfoR} from '@/api'

export const useCounterStore = defineStore('counter', {
    state: () => {
        const data: {
            token: string,
            userInfo: any,
            isLogin: boolean
        } = {
            token: getToken(),
            userInfo: getUserInfo(),
            isLogin: getLoginStatus(),
        }
        return data
    },
    actions: {
        setToken(token: string) {
            this.token = token
            setToken(token)
            return Promise.resolve(true)
        },
        async getUserInfo() {
            const res = await getUserInfoR()
            this.setUserInfo(res.data)
        },
        setUserInfo(data: any) {
            setUserInfo(data)
            this.userInfo = data
            this.isLogin = getLoginStatus()
        },
        login() {

        },
        logout() {
            uni.clearStorageSync()
            this.token = ''
            this.userInfo = {}
            this.isLogin = false
        }
    },
});

// 此导出的参数可以直接在js文件里调用
export const pinia = useCounterStore(createPinia())